﻿using Dapper;
using Dapper.Contrib.Extensions;
using Gx.Common.Core;
using Gx.Dal.Extensions;
using Gx.Dal.Shared;
using Gx.Model.Entity;
using Gx.Model.Enums;
using Gx.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gx.Dal.Manage
{
    public class LKWarehouseAdjustDal : BaseDal<LKWarehouseAdjust>
    {

        /// <summary>
        /// 名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool AnyName(string name)
        {
            using (var conn = new DbContext())
            {
                var total = conn.Connection.QueryFirst<int>("SELECT COUNT(1) FROM LK_WarehouseAdjust WITH(NOLOCK) WHERE IsDeleted=0 AND Name=@name", new { name });
                return total > 0;
            }
        }

        /// <summary>
        /// 获取最大编号
        /// </summary>
        /// <returns></returns>
        public string GetMaxLKWarehouseAdjustCode()
        {
            using (var conn = new DbContext())
            {
                //return conn.Connection.QueryFirst<string>("SELECT MAX(LKWarehouseAdjustCode) FROM LK_WarehouseAdjust WITH(NOLOCK)");
                return conn.Connection.QueryFirst<string>(@"SELECT MAX(CAST(SUBSTRING(BillNo, 2,LEN(BillNo)-1) AS int)) AS MaxBillNumber
FROM LK_WarehouseAdjust WITH(NOLOCK)
WHERE ISNUMERIC(SUBSTRING(BillNo, 2, LEN(BillNo) - 1)) = 1");
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedList<LKWarehouseAdjust> GetLKWarehouseAdjustPageList(LKWarehouseAdjustInput input)
        {
            string sql = @" SELECT DISTINCT a.* FROM dbo.LK_WarehouseAdjust a
 LEFT JOIN dbo.LK_WarehouseAdjustDetail d ON a.id=d.AdjustId AND d.IsDeleted=0
 WHERE a.IsDeleted=0 @WHERE";
            List<string> conditions = new List<string>();
            //判断input的属性是否为空，如果不为空则添加到conditions中

            if (!string.IsNullOrWhiteSpace(input.BillNo))
            {
                input.BillNo = $"%{input.BillNo}%";
                conditions.Add("a.BillNo LIKE @BillNo");
            }
            if (input.CustomerId.HasValue)
            {
                conditions.Add("a.CustomerId=@CustomerId");
            }
            if (input.BeginTime.HasValue)
            {
                conditions.Add("a.CreateTime>=@BeginTime");
            }
            if (input.EndTime.HasValue)
            {
                conditions.Add("a.CreateTime<=@EndTime");
            }

            if (!string.IsNullOrWhiteSpace(input.GoodsCode))
            {
                input.GoodsCode = $"%{input.GoodsCode}%";
                conditions.Add("d.GoodsNo LIKE @GoodsCode");
            }

            if (input.ModifyUserId.HasValue)
            {
                conditions.Add("a.ModifyUserId=@ModifyUserId");
            }
            if (input.ModifyBeginTime.HasValue)
            {
                conditions.Add("a.ModifyTime>=@ModifyBeginTime");
            }
            if (input.ModifyEndTime.HasValue)
            {
                conditions.Add("a.ModifyTime<=@ModifyEndTime");
            }

            if (UserContext.RoleId != (int)Roles.管理员)
            {
                conditions.Add($"CompanyId={UserContext.CompanyId}");
            }

            string condition = string.Empty;
            if (conditions.Any())
            {
                condition = $" AND {string.Join(" AND ", conditions)}";
            }
            sql = !string.IsNullOrWhiteSpace(condition) ? sql.Replace("@WHERE", condition) : sql.Replace("@WHERE", "");

            using (var conn = new DbContext())
            {
                return conn.Connection.GetPagedList<LKWarehouseAdjust>(sql, "CreateTime Desc", input);
            }
        }


        /// <summary>
        /// 添加调仓单
        /// </summary>
        /// <param name="lKWarehouseAdjustDto"></param>
        /// <returns></returns>
        public bool AddLKWarehouseAdjust(LKWarehouseAdjustDto lKWarehouseAdjustDto)
        {
            return UseTransaction((conn, trans) =>
            {
                var lKWarehouseAdjust = lKWarehouseAdjustDto.WarehouseAdjust;
                var result = conn.Insert(lKWarehouseAdjust, trans);

                var details = lKWarehouseAdjustDto.Details;
                if (details != null && details.Any())
                {
                    var adds = details.Where(c => c.Id == 0).ToList();
                    var updates = details.Where(c => c.Id > 0).ToList();


                    if (updates.Any())
                    {
                        conn.Update(updates, trans);

                        var upids = updates.Select(s => s.Id);
                        var deletes = conn.GetListByWhere<LKWarehouseAdjustDetail>("AdjustId=@adjustId AND Id Not IN @ids", new { adjustId = lKWarehouseAdjust.Id, ids = upids }, trans).Select(s => s.Id);
                        if (deletes.Any())
                        {
                            conn.DeleteByIds<LKWarehouseAdjustDetail, int>(deletes.ToList(), trans);
                        }
                    }
                    if (adds.Any())
                    {
                        adds.ForEach(item =>
                        {
                            item.AdjustId = lKWarehouseAdjust.Id;
                            item.CreateTime = DateTime.Now;
                        });
                        conn.Insert(adds, trans);

                        //修改入库单的仓库
                        foreach (var item in adds)
                        {
                            conn.Execute("UPDATE LK_WarehouseEntryDetail SET WareHouseId=@WareHouseId,WareHouseName=@WareHouseName WHERE GoodsNo = @GoodsNo", new { WarehouseId = item.InHouse, WareHouseName=item.InHouseName, item.GoodsNo }, trans);
                        }
                    }
                }

                var costs = lKWarehouseAdjustDto.Costs;
                if (costs != null && costs.Any())
                {
                    var adds = costs.Where(c => c.Id == 0).ToList();
                    var updates = costs.Where(c => c.Id > 0).ToList();

                    if (updates.Any())
                    {
                        conn.Update(updates);

                        var upids = updates.Select(s => s.Id);
                        var deletes = conn.GetListByWhere<LKWarehouseAdjustCost>("AdjustId=@adjustId AND Id Not IN @ids", new { adjustId = lKWarehouseAdjust.Id, ids = upids }, trans).Select(s => s.Id);
                        if (deletes.Any())
                        {
                            conn.DeleteByIds<LKWarehouseAdjustCost, int>(deletes.ToList(), trans);
                        }
                    }

                    if (adds.Any())
                    {
                        adds.ForEach(item =>
                        {
                            item.AdjustId = lKWarehouseAdjust.Id;
                            item.CreateTime = DateTime.Now;
                        });
                        conn.Insert(adds, trans);
                    }
                }

                return result > 0;
            });
        }

        public bool EditLKWarehouseAdjust(LKWarehouseAdjustDto lKWarehouseAdjustDto)
        {
            return UseTransaction((conn, trans) =>
            {
                var lKWarehouseAdjust = lKWarehouseAdjustDto.WarehouseAdjust;
                var result = conn.Update(lKWarehouseAdjust, trans);

                var details = lKWarehouseAdjustDto.Details;
                if (details != null && details.Any())
                {
                    var adds = details.Where(c => c.Id == 0).ToList();
                    var updates = details.Where(c => c.Id > 0).ToList();


                    if (updates.Any())
                    {
                        conn.Update(updates, trans);

                        var upids = updates.Select(s => s.Id);
                        var deletes = conn.GetListByWhere<LKWarehouseAdjustDetail>("AdjustId=@adjustId AND Id Not IN @ids", new { adjustId = lKWarehouseAdjust.Id, ids = upids }, trans).Select(s => s.Id);
                        if (deletes.Any())
                        {
                            conn.DeleteByIds<LKWarehouseAdjustDetail, int>(deletes.ToList(), trans);
                        }
                    }
                    if (adds.Any())
                    {
                        adds.ForEach(item =>
                        {
                            item.AdjustId = lKWarehouseAdjust.Id;
                            item.CreateTime = DateTime.Now;
                        });
                        conn.Insert(adds, trans);
                    }
                }

                var costs = lKWarehouseAdjustDto.Costs;
                if (costs != null && costs.Any())
                {
                    var adds = costs.Where(c => c.Id == 0).ToList();
                    var updates = costs.Where(c => c.Id > 0).ToList();

                    if (updates.Any())
                    {
                        conn.Update(updates, trans);

                        var upids = updates.Select(s => s.Id);
                        var deletes = conn.GetListByWhere<LKWarehouseAdjustCost>("AdjustId=@adjustId AND Id Not IN @ids", new { adjustId = lKWarehouseAdjust.Id, ids = upids }, trans).Select(s => s.Id);
                        if (deletes.Any())
                        {
                            conn.DeleteByIds<LKWarehouseAdjustCost, int>(deletes.ToList(), trans);
                        }
                    }

                    if (adds.Any())
                    {
                        adds.ForEach(item =>
                        {
                            item.AdjustId = lKWarehouseAdjust.Id;
                            item.CreateTime = DateTime.Now;
                        });
                        conn.Insert(adds, trans);
                    }
                }

                return result;
            });
        }

        public bool DeleteLKWarehouseAdjust(int id)
        {
            return UseTransaction((conn, trans) =>
            {
                var result = conn.Execute("UPDATE LK_WarehouseAdjust SET IsDeleted=1 WHERE Id=@id", new { id }, trans);
                conn.Execute("UPDATE LK_WarehouseAdjustDetail SET IsDeleted=1 WHERE AdjustId=@id", new { id }, trans);
                conn.Execute("UPDATE LK_WarehouseAdjustCost SET IsDeleted=1 WHERE AdjustId=@id", new { id }, trans);

                return result > 0;
            });
        }
    }
}

